const fs = require("fs");

//在/controllers里添加url-route

let addMapping = (router, mapping) => {
    for (var url in mapping) {
        if (url.startsWith("GET")) {
            var path = url.substring(4);
            router.get(path, mapping[url]);
            console.log(`register URL mapping:GET ${path}`);
        } else if (url.startsWith('POST')) {
            var path = url.substring(5);
            router.log(`register URL mapping:POST ${path}`);
        } else if (url.startsWith(`PUT`)) {
            var path = url.substring(4);
            router.put(path, mapping[url]);
            console.log(`register URL mapping：PUT ${path}`)
        } else {
            console.log(`invalid URL:${url}`)
        }
    }
}

function addControllers(router, dir) {
    fs.readdirSync(__dirname + '/' + dir).filter((f) => {
        return f.endsWith(".js");
    }).forEach((f) => {
        console.log(`process controller:${f}...`);
        let mapping = require(__dirname + '/' + dir + "/" + f);
        addMapping(router, mapping);
    });
}

module.exports = function (dir) {
    let
        controller_dir = dir || `controllers`,
        router = require('koa-router')();
    addControllers(router, controller_dir);
    return router.routes();
}